import cv2
import numpy as np
image=cv2.imread('C:\\Users\\20436\Desktop\duilian.jpg')
#获取宽和高
h=image.shape[0]
w=image.shape[1]

x1_min,x2_min,x3_min,x1_max,x2_max,x3_max=458,47,1088,856,192,1263
y1_min,y2_min,y3_min,y1_max,y2_max,y3_max=144,386,387,285,1145,1171

try:
    if not (x1_min,x2_min,x3_min>= 0 and y1_min,y2_min,y3_min >= 0 and x1_max,x2_max,x3_max < w and y1_max,y2_max,y3_max < h and x1_max,x2_max,x3_max > x1_min,x2_min,x3_min and y1_max,y2_max,y3_max > y1_min,y2_min,y3_min):
        raise ValueError('ROI区域设定有误！！！')
    # 切片（左闭右开）
    ROI_image = image.copy()[y1_min:y1_max, x1_min:x1_max]
    ROI_image1 = image.copy()[y2_min:y2_max, x2_min:x2_max]
    ROI_image2 = image.copy()[y3_min:y3_max, x3_min:x3_max]
    # 把要切出的区域花个框
    line_width = 2  # 框的宽度
    # 画出范围
    cv2.rectangle(
        image,
        (x1_min, y1_min),
        (x1_max, y1_max),
        (0, 0, 255),
        line_width
    )
    cv2.rectangle(
        image,
        (x3_min, y3_min),
        (x3_max, y3_max),
        (0, 0, 255),
        line_width
    )
    cv2.rectangle(
        image,
        (x2_min, y2_min),
        (x2_max, y2_max),
        (0, 0, 255),
        line_width
    )

except Exception as e:
    # 如果出错，弹出错误信息
    print('程序运行出错：', e)

# 3. 图片输出
cv2.imwrite('ROI_image.jpg', ROI_image)
cv2.imshow('ROI_image',ROI_image)
cv2.imshow('ROI_image1',ROI_image1)
cv2.imwrite('ROI_image1.jpg', ROI_image1)
cv2.imshow('ROI_image2',ROI_image2)
cv2.imwrite('ROI_image2.jpg', ROI_image2)
cv2.imshow('image_np', image)
cv2.imwrite('image.jpg', image)

cv2.waitKey(0)
